package com.guanghua.brick.security.extend;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.guanghua.brick.security.SecurityUtil;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class SecurityInterceptor implements Interceptor {
	
	private String noPermission = "NoPermission";
	private String function = null;

	public void destroy() {}

	public void init() {}

	public String intercept(ActionInvocation action) throws Exception {
		//获取调用的方法
		String m = action.getProxy().getMethod();
		m = (m!=null)?m:"execute";
		Method method = action.getAction().getClass().getMethod(m, (Class[])null);
		
		SecurityFunction sf = null;
		if (method != null) sf = (SecurityFunction)method.getAnnotation(SecurityFunction.class);
		
		//有annotation时，读取，并进行验证，没有的话就认为不需要验证
		String func = null;
		String[] orFunc = null;
		String[] andFunc = null;
		if (sf != null) {
			func = sf.function();
			orFunc = sf.orFunctions();
			andFunc = sf.andFunctions();
		} else if (function != null) {
			func = function;
		}
		
		//验证功能点
		if (func != null && func.length() != 0) {
			if (!SecurityUtil.functionPermissionValid(func, ServletActionContext.getRequest()))
				return getNoPermissionPage(ServletActionContext.getRequest(), func);
		//验证or关系的功能点，有其中一个通过即通过
		} else if (orFunc != null && orFunc.length != 0) {
			for (String f : orFunc) {
				if (SecurityUtil.functionPermissionValid(f, ServletActionContext.getRequest()))
					return action.invoke();
			}
		//验证or关系的功能点，有其中一个不通过即无权限,	
		} else if (andFunc != null && andFunc.length != 0) {
			for (String f : andFunc) {
				if (!SecurityUtil.functionPermissionValid(f, ServletActionContext.getRequest()))
					return getNoPermissionPage(ServletActionContext.getRequest(), func);
			}
		}
		
		return action.invoke();
	}
	
	
	//获取提示无权限页面
	private String getNoPermissionPage(HttpServletRequest req, String functionId) {
		req.setAttribute("functionName", SecurityUtil.getFunctionName(functionId, req));
		return this.noPermission;
	}

	public String getNoPermission() {
		return noPermission;
	}

	public void setNoPermission(String noPermission) {
		this.noPermission = noPermission;
	}
	
	public String getFunction() {
		return function;
	}

	public void setFunction(String function) {
		this.function = function;
	}
}
